package com.itmk.web.sys_user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.sys_user.entity.ChangePasswordParm;
import com.itmk.web.sys_user.entity.LoginParm;
import com.itmk.web.sys_user.entity.PageParm;
import com.itmk.web.sys_user.entity.SysUser;
import com.itmk.web.sys_user.service.SysUserService;
import com.itmk.web.user.entity.LoginResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;


@RestController
//该控制器的根路径为 /api/sysUser，所有方法的路径都会基于此路径。
@RequestMapping("/api/sysUser")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    //    新增用户
    @PostMapping
    public ResultVo add(@RequestBody SysUser sysUser) {
//        密码加密
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        //        将用户数据保存到数据库
        if (sysUserService.save(sysUser)) {
            return ResultUtils.success("add success");
        } else {
            return ResultUtils.error("add error");
        }
    }

    //    编辑用户
    @PutMapping
    public ResultVo edit(@RequestBody SysUser sysUser) {
        if (sysUserService.updateById(sysUser)) {
            return ResultUtils.success("edit success");
        } else {
            return ResultUtils.error("edit error");
        }
    }


    //    删除用户 ,通过id删除
    @DeleteMapping("/{userId}")
    public ResultVo del(@PathVariable("userId") int userId) {
        if (sysUserService.removeById(userId)) {
            return ResultUtils.success("delete success");
        } else {
            return ResultUtils.error("delete error");
        }
    }

    //    获取用户列表
    @GetMapping("/getList")
    public ResultVo getList(PageParm pageParm) {
        // 创建查询包装器
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        // 使用Lambda表达式构建查询条件，如果nickName不为空，则按nickName进行模糊查询
        queryWrapper.lambda().like(StringUtils.isNotEmpty(pageParm.getNickName()), SysUser::getNickName, pageParm.getNickName());
        // 创建分页对象，设置当前页和每页大小
        IPage<SysUser> page = new Page<>(pageParm.getCurrentPage(), pageParm.getPageSize());
        // 执行分页查询，获取用户列表
        IPage<SysUser> list = sysUserService.page(page, queryWrapper);
        // 返回查询结果，成功时返回包含用户列表的ResultVo对象
        return ResultUtils.success("get list success", list);
    }

    // 生成验证码
    @PostMapping("/captcha")
    public ResultVo captcha(HttpServletRequest request) {
        // 生成数字验证码 8653
        String text = defaultKaptcha.createText();

        // 把生成的验证码存到session里面
        HttpSession session = request.getSession();
        session.setAttribute("userCode", text);

        // 把数字验证码抓换成图片，base64
        BufferedImage bufferedImage = defaultKaptcha.createImage(text);
        ByteArrayOutputStream outputStream = null;
        try {
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);

            // 使用Java 8的Base64编码器
            String base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            String captchaBase64 = "data:image/jpeg;base64," + base64.replaceAll("\r\n", "");

            // 返回结果
            ResultVo result = new ResultVo("生成成功", 200, captchaBase64);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultVo("生成失败", 500, null);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 登录接口
    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginParm parm, HttpServletRequest request) {
        // 验证码验证
        HttpSession session = request.getSession();
        String userCode = (String) session.getAttribute("userCode"); // 从session里面获取验证码
        String code = parm.getCode(); // 从前端传递过来的验证码

        if (StringUtils.isEmpty(userCode)) {
            return ResultUtils.error("验证码过期!");
        }

        // 对比验证码
        if (!userCode.equalsIgnoreCase(code)) {
            return ResultUtils.error("验证码错误!");
        }

        // 用户查询
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.lambda()
                .eq(SysUser::getUserName, parm.getUserName())
                .eq(SysUser::getPassword, DigestUtils.md5DigestAsHex(parm.getPassword().getBytes())); // 添加密码加密
        SysUser one = sysUserService.getOne(query);

        if (one == null) {
            return ResultUtils.error("用户名或者密码错误!");
        }
        if (one.getStatus().equals("0")) {
            return ResultUtils.error("该管理员账户已停用!");
        }
        // 登录成功，返回用户信息
        LoginResponse resp = new LoginResponse();
        resp.setUserId(one.getUserId());
        resp.setNickname(one.getNickName());

        return ResultUtils.success("登录成功!", resp);
    }


//    修改密码
    @PutMapping("/changePassword")
    public ResultVo changePassword(@RequestBody ChangePasswordParm parm) {
        SysUser sysUser = sysUserService.getById(parm.getUserId());
        if (sysUser == null) {
            return ResultUtils.error("用户不存在");
        }
        if (!sysUser.getPassword().equals(DigestUtils.md5DigestAsHex(parm.getOldPassword().getBytes()))) {
            return ResultUtils.error("原密码错误");
        }
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(SysUser::getPassword, DigestUtils.md5DigestAsHex(parm.getNewPassword().getBytes()))
                .eq(SysUser::getUserId, parm.getUserId());
        if (sysUserService.update(updateWrapper)) {
            return ResultUtils.success("修改密码成功");

        }
        return ResultUtils.error("修改密码失败");



        }



}

